package com.wanghua.spring.action;

import com.opensymphony.xwork2.ActionSupport;
import com.wanghua.spring.bean.entity.VisitDetail;
import com.wanghua.spring.bean.entity.VisitOnline;
import com.wanghua.spring.service.IVisitDetailService;
import com.wanghua.spring.util.IpUtil;
import com.wanghua.spring.util.Pagination1;
import com.wanghua.spring.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Date;
import java.util.List;

/*
* 我发现请求是会被缓存的，导致有时候断点插了无效。这时修改下URL就可以了，应该内部是用URL作为 key来缓存的。可能与配了 EhCache 有关。
* */

//Spring负责生成Action对象。id属性值对应 struts.xml中<action>的class属性值。因为Struts2的Action不是单个实例，因此scope属性需要配置为 prototype。
@Scope("prototype")
@Controller("visitDetailAction")
public class VisitDetailAction extends ActionSupport {
    protected Log log = LogFactory.getLog(getClass());

    //XML AOP事务管理使用在 Service层，这里 Control层必须使用 IService接口，不能使用实现类，否则AOP事务管理会报错。
    @Resource   //Spring注射进来的。这是 JSR-250 规范定义的注释，按 byName 自动注入。
    private IVisitDetailService visitDetailService;

    /**
     * 接收 JavaScript 提交的数据，这个属性并不是Spring注射进来的。
     * 注意：这个属性必须是 JavaBean，即有 get、set。这样才能接收 Javacript 提交的数据。
     * 例如，Get请求格式：http://localhost:8080?userid=1420263235391&v.reffer=&v.screenWidth=1366&v.screenHeight=768&v.colorDepth=24&v.appName=Netscape。
     * 如果URL参数中没有传递 v. 属性，那么这里的 v等于null，只要传递了一个就不会为null。
     */
    private VisitDetail v;

    private Pagination1 pagination;

    @Override
    public String execute() throws  Exception{
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpSession session = request.getSession(true);

        String action = request.getParameter("action");
        if ("listDetail".equals(action)) {
            return visitDetail();
        }
        if ("listOnline".equals(action)) {
            return visitOnline();
        }

        return visitAdd();
    }

    public String visitAdd() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpSession session = request.getSession(true);

        //设置超时的用户为离线
        visitDetailService.removeTimedOutOnlineRecords();

        String ip = request.getRemoteAddr();
        if (StringUtil.isNull(v.getUrl())) {
            v.setUrl(request.getHeader("Referer"));
        }

        v.setIp(ip);
        v.setAddress(IpUtil.getIpAddress(ip));
        v.setUserAgent(request.getHeader("User-Agent"));
        v.setDate(new Date(System.currentTimeMillis()));
        v.setKeyword(StringUtil.getParameter(v.getReffer()));

        visitDetailService.create(v);

        String userid = request.getParameter("userid");
        VisitOnline online = visitDetailService.findValidOnline(v.getIp(), userid);
        if (online == null) {
            online = new VisitOnline();
            online.setActiveTimes(1);
            online.setStartDate(new Date(System.currentTimeMillis()));
            online.setLastActiveDate(new Date(System.currentTimeMillis()));
            online.setIp(v.getIp());
            online.setAddress(v.getAddress());
            online.setOnline(true);
            online.setUrl(v.getUrl());
            online.setTitle(v.getTitle());
            online.setUserid(userid);
            online.setScreenWidth(v.getScreenWidth());
            online.setScreenHeight(v.getScreenHeight());
            online.setColorDepth(v.getColorDepth());
            online.setAppName(v.getAppName());
            online.setUserAgent(v.getUserAgent());
            visitDetailService.create(online); //也可以用 visitDetailService.save(online);
        } else {
            online.setActiveTimes(online.getActiveTimes() + 1);
            online.setLastActiveDate(new Date(System.currentTimeMillis()));
            online.setTitle(v.getTitle());
            online.setUrl(v.getUrl());
            visitDetailService.save(online);
        }
        if (!StringUtil.isNull(v.getErr())) {
            log.error("Error: " + v.getErr());
        }

        try {
            return "logo"; //返回统计图标
        } catch (Throwable ex) {
            String msg = ex.getMessage();
        }
        return "logo";
    }

    //请求：http://localhost:81/visitDetail?v.sort=id&v.order=desc
    public String visitDetail() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpSession session = request.getSession(true);

        String sort = StringUtil.isNull(v) ? null : v.getSort();
        String order = StringUtil.isNull(v) ? null : v.getOrder();
        if (StringUtil.isNull(sort)) {
            sort = "id";
        }
        if (StringUtil.isNull(order)) {
            order = "desc";
        }

        String hql = " from VisitDetail v ";
        hql += " order by " + sort + " " + order;

        int count = visitDetailService.getTotalCount(" select count(v) " + hql);

        Pagination1 pagination = new Pagination1(request, response);
        pagination.setRecordCount(count);

        List detailList = visitDetailService.list(hql, pagination.getFirstResult(), pagination.getPageSize());

        request.setAttribute("url", StringUtil.getURL(request));
        request.setAttribute("sort", sort);
        request.setAttribute("order", order);
        request.setAttribute("pagination", pagination);
        request.setAttribute("detailList", detailList);

        return "listDetail";
    }

    //请求：http://localhost:81/visitOnline?v.sort=id&v.order=desc
    public String visitOnline() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpSession session = request.getSession(true);

        String sort = StringUtil.isNull(v) ? null : v.getSort();
        String order = StringUtil.isNull(v) ? null : v.getOrder();
        if (StringUtil.isNull(sort)) {
            sort = "id";
        }
        if (StringUtil.isNull(order)) {
            order = "desc";
        }

        String hql = " from VisitOnline v order by " + sort + " " + order;
        int count = visitDetailService.getTotalCount(" select count(v) " + hql);

        Pagination1 pagination = new Pagination1(request, response);
        pagination.setRecordCount(count);

        List onlineList = visitDetailService.list(hql, pagination.getFirstResult(), pagination.getPageSize());

        request.setAttribute("url", StringUtil.getURL(request));
        request.setAttribute("order", order);
        request.setAttribute("pagination", pagination);
        request.setAttribute("onlineList", onlineList);

        return "listOnline";
    }

    @PostConstruct
    public void postConstruct1(){
        System.out.println("Bean 已初始化！");
    }
    @PreDestroy  //@PreDestroy则在JVM退出的ShutdonwHook中拦截，注意，ShutdownHook对kill -9这种暴烈的关闭无效。
    public void preDestroy1() {
        System.out.println("Bean 准备销毁了！");
    }

    public IVisitDetailService getVisitDetailService() {
        return visitDetailService;
    }

    public void setVisitDetailService(IVisitDetailService visitDetailService) {
        this.visitDetailService = visitDetailService;
    }

    public VisitDetail getV() {
        return v;
    }

    public void setV(VisitDetail v) {
        this.v = v;
    }

    public Pagination1 getPagination() {
        return pagination;
    }

    public void setPagination(Pagination1 pagination) {
        this.pagination = pagination;
    }
}
